﻿/**
 * 表格的编辑功能。
 */
Ext.define('Happy.table.action.Edit', {
    extend: 'Happy.table.action.ShowAction',
    alias: 'action.edit',
    requires: [
        'Happy.Ajax',
        'Happy.Msg'
    ],

    /**
     * @inheritdoc
     */
    defaultConfig: {
        itemId: 'edit',
        iconCls: 'edit-button',
        text: '编辑',
        disabled: true,
        autoEnableAndDisable: true,
        formContainer: null,
        tableSelector: 'tablepanel',
        remoteLoad: true
    },

    /**
     * @inheritdoc
     */
    onClickHandler: function (button) {
        var me = this;

        var table = me.up(button, me.initialConfig.tableSelector);
        var record_i = table.getFirstSelected();

        if (me.initialConfig.remoteLoad === true) {
            Happy.Ajax.load(record_i.self, record_i.getId(), {
                success: function (record_j) {
                    me.showRecord(table, record_j);
                },
                failure: function (rec, operation) {
                    Happy.Msg.showLoadFailure(operation.error);
                }
            });
        }
        else {
            me.showRecord(table, record_i);
        }
    },

    /**
     * @inheritdoc
     */
    onContainerShow: function (container, table, record) {
        var me = this;

        var form = container.down('form');

        form.on('remoteupdatesuccess', Ext.bind(me.onRemoteUpdateSuccessHandler, me, [table], true));
        form.loadRecord(record);
    },

    /**
     * 记录远程更新成功时的处理方法。
     * 
     * @private
     */
    onRemoteUpdateSuccessHandler: function (form, record, table) {
        var selRecord = table.selectAndReturnRecord(record.getId());

        if (selRecord != record) {
            selRecord.set(record.getData());
        }

        table.updateRecord(selRecord);
        //这句话会将表格的未提交标志（一个红色小旗）给去掉。
        selRecord.commit();
    }
});